import React from "react";
import { createBrowserRouter, Navigate, useNavigate } from "react-router-dom";
import AdminLayout from "../layouts/AdminLayout";
import StudentLayout from "../layouts/StudentLayout";
import TeacherLayout from "../layouts/TeacherLayout";
import AdminHome from "../pages/admin/Home";
import TeacherManagement from "../pages/admin/Teachers";
import StudentManagement from "../pages/admin/Students";
import CourseManagement from "../pages/admin/Courses";
import DiscussionManagement from "../pages/admin/Discussion";
import StudentHome from "../pages/student/Home";
import StudentCourses from "../pages/student/Courses";
import StudentDiscussion from "../pages/student/Discussion";
import TeacherHome from "../pages/teacher/Home";
import TeacherCourses from "../pages/teacher/Courses";
import TeacherDiscussion from "../pages/teacher/Discussion";
import Login from "../pages/common/Login";
import { useUser } from "../contexts/UserContext";
import { Result, Button, message, Spin } from "antd";
import TeacherPreparation from "../pages/teacher/Preparation";
import TeacherClassManagement from "../pages/teacher/ClassManagement";
import TeacherExamGeneration from "../pages/teacher/ExamGeneration";
import TeacherAnalysis from "../pages/teacher/Analysis";
import TeacherResources from "../pages/teacher/Resources";
import StudentExams from "../pages/student/Exams";
import StudentResources from "../pages/student/Resources";
import UserProfile from "../components/UserProfile";
import Dashboard from "../pages/admin/Dashboard";

interface PrivateRouteProps {
  element: React.ReactElement;
  requiredRole?: "admin" | "teacher" | "student";
}

const ErrorBoundary: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useUser();

  const getHomeRoute = () => {
    if (!user) return "/login";
    switch (user.role) {
      case "admin":
        return "/admin";
      case "teacher":
        return "/teacher";
      case "student":
        return "/student";
      default:
        return "/login";
    }
  };

  return (
    <Result
      status="500"
      title="系统错误"
      subTitle="抱歉，系统出现了一些问题。"
      extra={[
        <Button
          type="primary"
          key="home"
          onClick={() => navigate(getHomeRoute())}
        >
          返回首页
        </Button>,
        <Button key="retry" onClick={() => window.location.reload()}>
          重新加载
        </Button>,
      ]}
    />
  );
};

const PrivateRoute: React.FC<PrivateRouteProps> = ({
  element,
  requiredRole,
}) => {
  const { user, loading } = useUser();
  const navigate = useNavigate();

  React.useEffect(() => {
    if (!loading && !user) {
      message.error("请先登录");
      navigate("/login", { replace: true });
    } else if (!loading && requiredRole && user?.role !== requiredRole) {
      message.error("您没有权限访问该页面");
      navigate("/", { replace: true });
    }
  }, [loading, user, navigate, requiredRole]);

  if (loading) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!user) {
    return null;
  }

  if (requiredRole && user.role !== requiredRole) {
    return (
      <Result
        status="403"
        title="无权访问"
        subTitle="抱歉，您没有权限访问该页面"
        extra={
          <Button type="primary" onClick={() => navigate("/")}>
            返回首页
          </Button>
        }
      />
    );
  }

  return element;
};

const router = createBrowserRouter([
  {
    path: "/",
    element: <Navigate to="/login" replace />,
    errorElement: <ErrorBoundary />,
  },
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/admin",
    element: <PrivateRoute element={<AdminLayout />} requiredRole="admin" />,
    errorElement: <ErrorBoundary />,
    children: [
      {
        path: "",
        element: <AdminHome />,
      },
      {
        path: "profile",
        element: <UserProfile />,
      },
      {
        path: "teachers",
        element: <TeacherManagement />,
      },
      {
        path: "students",
        element: <StudentManagement />,
      },
      {
        path: "courses",
        element: <CourseManagement />,
      },
      {
        path: "discussions",
        element: <DiscussionManagement />,
      },
    ],
  },
  {
    path: "/teacher",
    element: (
      <PrivateRoute element={<TeacherLayout />} requiredRole="teacher" />
    ),
    errorElement: <ErrorBoundary />,
    children: [
      {
        path: "",
        element: <TeacherHome />,
      },
      {
        path: "profile",
        element: <UserProfile />,
      },
      {
        path: "courses",
        element: <TeacherCourses />,
      },
      {
        path: "preparation",
        element: <TeacherPreparation />,
      },
      {
        path: "class-management",
        element: <TeacherClassManagement />,
      },
      {
        path: "exam-generation",
        element: <TeacherExamGeneration />,
      },
      {
        path: "analysis",
        element: <TeacherAnalysis />,
      },
      {
        path: "resources",
        element: <TeacherResources />,
      },
      {
        path: "discussions",
        element: <TeacherDiscussion />,
      },
    ],
  },
  {
    path: "/student",
    element: (
      <PrivateRoute element={<StudentLayout />} requiredRole="student" />
    ),
    errorElement: <ErrorBoundary />,
    children: [
      {
        path: "",
        element: <StudentHome />,
      },
      {
        path: "profile",
        element: <UserProfile />,
      },
      {
        path: "courses",
        element: <StudentCourses />,
      },
      {
        path: "exams",
        element: <StudentExams />,
      },
      {
        path: "resources",
        element: <StudentResources />,
      },
      {
        path: "discussions",
        element: <StudentDiscussion />,
      },
    ],
  },
]);

export { router };
